<template>
  <div class="modify-information">
    <el-page-header @back="$router.go(-1)" content="修改资料" />
    <!-- 1232 -->
    <div class="content-main modify-fields-wrap flex-center">
      <div class="modify-fields">
        <el-input v-model="sendForm.company" class="margin--top" placeholder="请输入所在公司" />
        <el-input
          v-model="sendForm.github"
          class="margin--top"
          placeholder="请输入Github, 默认为https://"
        />
        <el-input v-model="sendForm.web" class="margin--top" placeholder="请输入个人主页, 默认为https://" />
        <el-input v-model="sendForm.information" class="margin--top" placeholder="请输入个性签名" />

        <div class="operations-btn flex-evenly">
          <el-button @click="resetFieldInput">置空</el-button>
          <el-button type="primary" @click="submitFieldInput">提交</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import API from '~/interface/User';
export default {
  head() {
    return {
      title: '修改资料 - [rabbit-pie]'
    }
  },

  data() {
    return {
      sendForm: {
        uid: '',
        web: '',
        cover: '',
        github: '',
        company: '',
        portrait: '',
        information: ''
      }
    }
  },

  created() {
    this.getCurrentUserInfo();
  },

  methods: {
    getCurrentUserInfo() {
      let id = this.$route.params.uid;
      API.getUserDetail(id).then(res => {
        this.sendForm = res;
      }).catch(err => {
        if (err.code === 10002 || err.msg === '用户不存在') {
          this.$router.go(-1);
        }
      });
    },
    resetFieldInput() {
      let form = this.sendForm;

      for (let key in form) {
        form[key] = '';
      }
    },
    submitFieldInput() {
      let httpReg = /(http|https):\/\/([\w.]+\/?)\S*/;

      if (!httpReg.test(this.sendForm.web)) {
        this.sendForm.web = 'https://' + this.sendForm.web.trim()
      }

      if (!httpReg.test(this.sendForm.github)) {
        this.sendForm.github = 'https://' + this.sendForm.github.trim()
      }

      API.postUserInformation(this.sendForm).then(res => {
        this.$router.go(-1);
        this.$message({
          type: 'success',
          message: '用户资料修改成功~'
        });
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.modify-fields-wrap {
  .modify-fields {
    width: 500px;
  }

  .operations-btn {
    width: 300px;
    margin: 30px auto 0;
  }
}
</style>